import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { ModalController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Storage } from '@ionic/storage';
import { TranslateService } from '@ngx-translate/core';

import { HomePage } from '../pages/home/home';
import { ActivatePage } from '../pages/activate/activate';
import { LoginPage } from '../pages/login/login';
import { ListPage } from '../pages/list/list';
import { TableListPage } from '../pages/table-list/table-list';
import { CurrentOrderPage } from '../pages/current-order/current-order';
import { ProductListPage } from '../pages/product-list/product-list';
import { ProductOptionModalPage } from '../pages/product-option-modal/product-option-modal';
import { ProductOptionListPage } from '../pages/product-option-list/product-option-list';
import { OrderHistoryPage } from '../pages/order-history/order-history';
import { SettingsPage } from '../pages/settings/settings';
import { ServerQrCodePage } from '../pages/server-qr-code/server-qr-code';
import { HelperService } from "../providers/services.helper";
import { ApiService } from "../providers/services.api";
import { OfflineService } from "../providers/services.offline";
import { PrinterService } from "../providers/services.printer";
import { GlobalData } from "../providers/GlobalData";

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = null;
  backButtonPressed: boolean = false;

  pages: Array<{ title: string, code: string, component: any, isShow: boolean }>;

  constructor(public platform: Platform,
    public modalCtrl: ModalController,
    public statusBar: StatusBar,
    private storage: Storage,
    public splashScreen: SplashScreen,
    public translate: TranslateService,
    public helperService: HelperService,
    public api: ApiService,
    public offline: OfflineService,
    public printer: PrinterService,
    public global: GlobalData) {

    this.initializeApp().then(isPlatformReady => {
      if (isPlatformReady) {
        this.initLocalStorage().then(component => {
          console.log(component);
          this.nav.setRoot(component);
        });
        this.initTranslate();
      }
    });

  }

  initLocalStorage() {
    return new Promise<any>(resolve => {
      this.storage.get('activate').then((activate) => {
        if (activate == null) {
          this.storage.set('activate', {
            status: false,
            path: 'www',
            prefix: 'sandbox.',
            passcode: '',
            shop_icon: ''
          });
        }
        console.log('localstorage activate is', activate);

        this.storage.get('settings').then((setting) => {
          this.storage.get('user').then((user) => {
            if (user == null) {
              this.storage.set('user', {
                id: null,
                name: null,
                shop_id: null,
                level: null,
                login: '',
                password: '',
                isLogin: false,
                warehouse: null
              });
            }
            console.log('localstorage user is', user);

            if (setting == null) {
              this.storage.set('settings', {
                token: 'empty_token',
                locale: 'EN_US',
                print_locale: 'EN_US',
                device_type: '',
                device_token: '',
                warehouse_lock: false,
                warehouse_id: '',
                warehouse: null,
                departments: null,
                epsonPrinters: null,
                cloud_lock: false,
                login_save: true,
                cloud_address: '',
                epson_ip_address: '192.168.1.23',
                epson_port: '8008',
                epson_device_id: 'local_printer',
                printer_type: 'EPSON thermal printer',
                online_mode: true,
                sandbox_mode: false,
                is_print_by_department: false,
                decimal_point: 1,
                device_prefix: ''
              });
            }
            console.log('localstorage setting is', setting);

            if (activate == null || !activate.status) {
              console.log('go to activation');
              resolve(ActivatePage);
            } else if (!user.isLogin) {
              resolve(LoginPage);
            } else {
              resolve(HomePage);
            }
          });
        });
      });
    });
  }

  initializeApp() {
    // console.log(this.nativeStorage.getItem('activate'));
    return new Promise<boolean>(resolve => {
      this.platform.ready().then(() => {
        // Okay, so the platform is ready and our plugins are available.
        // Here you can do any higher level native things you might need.
        this.statusBar.styleDefault();
        this.splashScreen.hide();
        resolve(true);
      });
    });
  }

  initTranslate() {
    // Set the default language for translation strings, and the current language.
    this.translate.setDefaultLang('EN_US');
    this.translate.use('EN_US'); // Set your language here
  }

  // order history
  orderHistory() {
    let modal = this.modalCtrl.create(OrderHistoryPage);
    modal.present();
  }

  // settings
  settings() {
    let modal = this.modalCtrl.create(SettingsPage);
    modal.onDidDismiss(data => {
      console.log(data);
      if (data != null && data == 'tologin') {
        console.log('to login');
        this.storage.get('user').then((user) => {
          user.isLogin = false;
          this.storage.set('user', user);
        });
        this.nav.setRoot(LoginPage);
      }
    });
    modal.present();
  }

  // settings
  logOut() {
    this.storage.get('user').then((user) => {
      user.isLogin = false;
      this.storage.set('user', user);
    });
    this.nav.setRoot(LoginPage);
  }

  showExit() {
    if (this.backButtonPressed) {
      this.platform.exitApp();
    } else {
      this.helperService.showToast(this.translate.instant('PRESS_ONCE_MORE_TO_EXIT'));
      this.backButtonPressed = true;
      setTimeout(() => {
        this.backButtonPressed = false;
      }, 2000)
    }
  }
}
